<template>
  <div class="main_box">
    <el-row class="header-row">
      <el-col>
        <div class="search_wrap">
          <el-form :inline="true" ref="searchForm" :model="searchForm">
            <el-form-item prop="msgType" label="消息类型:">
              <el-select v-model="searchForm.msgType" :clearable="true" placeholder="请选择消息类型">
                <el-option v-for="item in msgType" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="msgStatus" label="消息状态:">
              <el-select v-model="searchForm.msgStatus" :clearable="true" placeholder="请选择消息状态">
                <el-option v-for="item in msgStatue" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item prop="date" label="查询日期:">
              <el-date-picker
                v-model="searchForm.date"
                :clearable="true"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="['00:00:00', '23:59:59']"
              ></el-date-picker>
            </el-form-item>

            <el-form-item>
              <el-button icon="el-icon-search" type="primary" @click="onSearch">查询</el-button>
              <el-button icon="el-icon-refresh-left" @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
      <el-col>
        <div class="opration_wrap">
          <el-tooltip content="刷新" placement="top">
            <el-button circle icon="el-icon-refresh-right" @click="reload" size="mini"></el-button>
          </el-tooltip>
          <div>
            <el-button size="mini" type="success" plain icon="el-icon-finished" @click="cleanAllMsg">全部已读</el-button>
            <el-button size="mini" type="info" icon="el-icon-document-checked" plain @click="cleanMsgStatus">已读</el-button>
            <!-- <el-button v-has="permissionAdd" type="primary" plain icon="fa fa-plus" @click="handleClickAdd()" size="mini"> 新增</el-button> -->
          </div>
        </div>
      </el-col>
    </el-row>

    <el-row ref="tableRow">
      <el-table ref="tableList" :data="tableList" :fit="true" @row-click="$refs.tableList.toggleRowSelection($event)" @selection-change="changeSelect">
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column type="index" label="序号" width="60"></el-table-column>
        <el-table-column prop="remindType" label="消息类型" width="230">
          <template slot-scope="scope">
            <span v-if="scope.row.remindType == 1"> 系统消息 </span>
            <span v-if="scope.row.remindType == 2"> 订单消息 </span>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="sourceName" label="消息来源" width="250" align="center"></el-table-column> -->
        <el-table-column prop="remindContent" label="消息内容" width="550" align="center"></el-table-column>
        <el-table-column prop="isRead" label="消息状态" :formatter="formatIsRead" width="180" align="center"></el-table-column>
        <el-table-column prop="createDate" label="消息时间" width="200" align="center"></el-table-column>
        <el-table-column prop="createUserName" label="创建人" width="120" align="center"></el-table-column>
        <el-table-column label="操作" width="300" align="center">
          <template slot-scope="scope">
            <el-row>
              <el-button v-if="scope.row.remindType == 2" @click="handleSearch(scope.row)" size="mini">前往查看</el-button>
              <!-- 报告单操作 -->
            </el-row>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.pageNo"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="page.pageSize"
        layout="total, sizes, jumper, next, pager, prev"
        :total="page.pageTotal"
      ></el-pagination>
    </el-row>
  </div>
</template>

<script>
import MessageApi from '@/api/message/message';
import AuthApi from '@/api/system/auth';
import { getStorage } from '@/utils/auth';
import * as stn from '@/constants/storeName';
import { mapActions } from 'vuex';

export default {
  name: 'MessageManagement',
  inject: ['reload'], //注入局部刷新
  data() {
    return {
      userInfo: {}, // 获取当前登陆用户信息
      loadingIns: false,
      searchForm: {
        msgType: '',
        msgStatus: '0',
        date: [],
      },
      tableList: [],
      selectIds: [],

      page: {
        pageNo: 1,
        pageSize: 20,
        pageTotal: 0,
      },
      msgType: [
        { label: '系统', value: 1 },
        { label: '订单', value: 2 },
      ],
      msgStatue: [
        { label: '未读', value: '0' },
        { label: '已读', value: '1' },
      ],
      permissionAdd: 'SYSTEM_MANAGER_MESSAGE_MESSAGE_LIST_ADD',
    };
  },
  components: {
    // uploadFile
  },
  mounted() {
    this.userInfo = getStorage(stn.USER_INFO);
    this.initDate();
    this.getTableHeight();
    this.listTable();
    // this.listHospital();
    window.addEventListener('keydown', this.keyDown);
  },
  destroyed() {
    window.removeEventListener('keydown', this.keyDown, false);
  },
  methods: {
    ...mapActions({
      setUnReadCount: 'setUnReadCount',
    }),
    keyDown(e) {
      //如果是回车则执行查询方法
      if (e.keyCode == 13) {
        this.onSearch();
      }
    },
    getTableHeight() {
      this.$nextTick(function () {
        this.maxHeight = window.innerHeight - this.$refs.tableRow.$el.offsetTop - 50;
        window.onresize = () => {
          this.maxHeight = window.innerHeight - this.$refs.tableRow.$el.offsetTop - 50;
        };
      });
    },
    listTable() {
      let data = {
        pageNo: this.page.pageNo,
        pageSize: this.page.pageSize,
        remindType: this.searchForm.msgType,
        isRead: this.searchForm.msgStatus,
      };
      if (this.searchForm.date && this.searchForm.date.length == 2) {
        data.createDateBegin = this.$Utils.formatDate(this.searchForm.date[0], 'yyyy-MM-dd hh:mm:ss');
        data.createDateEnd = this.$Utils.formatDate(this.searchForm.date[1], 'yyyy-MM-dd hh:mm:ss');
      }
      this.$emit('show-loading', true);
      MessageApi.listRemind(data)
        .then((res) => {
          this.tableList = res.data.list;
          this.page.pageTotal = res.data.total;
          this.$refs.tableList.bodyWrapper.scrollTop = 0;
          this.$emit('show-loading', false);
        })
        .catch((error) => {
          console.error(error);
          this.$emit('show-loading', false);
        });
    },
    onSearch() {
      this.page.pageNo = 1;
      this.listTable();
    },
    resetForm() {
      this.searchForm.msgType = '';
      this.searchForm.msgStatus = '';
      this.onSearch();
    },
    changeSelect(val) {
      this.selectIds = [];
      for (let i = 0; i < val.length; i++) {
        //console.log(JSON.stringify(val[i]))
        let id = val[i].remindId;
        this.selectIds.push(id);
      }
    },
    formatIsRead(row, column, cellValue) {
      return cellValue === 1 ? '已读' : '未读';
    },
    handleSearch(row) {
      this.$router.push({ path: '/order/orderManagement' });
    },
    cleanAllMsg() {
      let _this = this;
      MessageApi.updateMsgRead({ remindIds: '' })
        .then((res) => {
          _this.listTable();
          _this.getMsgStatus();
        })
        .catch((error) => {
          console.error(error);
        });
    },

    getMsgStatus() {
      let _this = this;
      MessageApi.getRemindMinute({}).then((res) => {
        this.setUnReadCount(res.data.unreadCount);
        if (res.data.unreadCount === 0) {
          _this.$emit('clear-msg-dot');
        }
      });
    },
    cleanMsgStatus() {
      if (this.selectIds.length > 0) {
        let ids = '';
        for (let i = 0; i < this.selectIds.length; i++) {
          ids += this.selectIds[i] + ',';
        }
        ids = ids.substring(0, ids.length - 1);
        let _this = this;
        MessageApi.updateMsgRead({ remindIds: ids }).then((res) => {
          _this.getMsgStatus();
          _this.listTable();
        });
      } else {
        this.$Utils.notifyError('请选择对应消息');
      }
    },
    initDate() {
      let begin = new Date();
      let nowYear = begin.getFullYear();
      begin.setFullYear(nowYear, 0, 1);
      begin.setHours(0);
      begin.setMinutes(0);
      begin.setSeconds(0);
      // begin.setDate(1);
      let end = new Date();
      end.setHours(23);
      end.setMinutes(59);
      end.setSeconds(59);
      this.searchForm.date = [begin, end];
    },
    handleSizeChange(size) {
      this.page.pageSize = size;
      this.listTable();
    },
    handleCurrentChange(val) {
      this.page.pageNo = val;
      this.listTable();
    },
    formatMsgStatus(row, column, cellValue) {
      if (cellValue === -1) {
        return '全部';
      } else if (cellValue === 0) {
        return '未读';
      } else if (cellValue === 1) {
        return '已读';
      }
    },
  },
};
</script>

<style lang="scss">
@import '@/assets/css/views/content.scss';
</style>
